<?php

namespace app\admin\controller;

use app\common\model\AdminLogModel;
use app\common\model\UserModel;
use app\common\model\UserProfitModel;
use app\common\model\WorldCupGameModel;
use app\common\model\WorldCupGameOrderModel;
use think\Db;
use think\db\Query;

class WorldCupGuessController extends BaseController
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $model = WorldCupGameModel::field('*');
            if (in_array($group_code = $this->get('group_code'), ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'])) {
                $model = $model->where('group_code', $group_code);
            }

            return json([
                'count' => $model->count('id'),
                'list' => $model->order('id', 'desc')
                    ->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()->each(function ($query) {
                        if ($diamond = WorldCupGameOrderModel::where('team_id', $query->id)->sum('diamond')) {
                            $diamond = bcdiv($diamond, '100', 2);
                        }

                        if ($settle_diamond = WorldCupGameOrderModel::where('team_id', $query->id)->where('status', 2)->sum('settle_diamond')) {
                            $settle_diamond = bcdiv($settle_diamond, '100', 2);
                        }

                        $query->diamond = $diamond;
                        $query->settle_diamond = $settle_diamond;
                    })
                    ->toArray(),
                'code' => 0,
                'msg' => ''
            ]);
        }

        return $this->fetch();
    }

    public function setOdds()
    {
        if (!ctype_digit($id = $this->post('id', ''))) {
            return static::bulidFail('球队ID不能为空');
        }

        if (!is_numeric($odds = $this->post('odds', ''))) {
            return static::bulidFail('赔率错误');
        }

        if (!$model = WorldCupGameModel::where('id', $id)->find()) {
            return static::bulidFail('球队不存在');
        }

        $model->odds = $odds;
        if (!$model->save()) {
            return static::bulidFail('调整赔率失败');
        }

        $this->addAdminLog('成功调整了 ' . $model->team_name . ' 赔率为' . $odds);

        return static::bulidSuccess([], '调整赔率成功');
    }

    public function eliminate()
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        if (!ctype_digit($id = $this->post('id', ''))) {
            return static::bulidFail('球队ID不能为空');
        }

        if (!$model = WorldCupGameModel::where('id', $id)->lock()->find()) {
            return static::bulidFail('球队不存在');
        }

        if ($model->open_status == 2) {
            return static::bulidFail('该球队已淘汰 不可再次设置');
        }

        if (WorldCupGameModel::where('open_status', 0)->count('id') == 1) {
            return static::bulidFail('世界杯比赛赛事不能全部设置为淘汰 有并且只有一场胜出');
        }

        $model->status = 2;
        $model->open_status = 2;

        Db::startTrans();

        try {
            if (!$model->save()) {
                Db::rollback();
                return static::bulidFail('设置淘汰失败');
            }

            WorldCupGameOrderModel::where('team_id', $id)
                ->where('status', 1)
                ->chunk(100, function ($orders) {
                    foreach ($orders as $order) {
                        $order->settle_diamond = $order->diamond;
                        $order->status = 3;
                        if (!$order->save()) {
                            throw new \Exception('订单处理失败');
                        }
                    }
                });

            Db::commit();

            $this->addAdminLog('成功设置了 ' . $model->team_name . ' 为淘汰');
            return static::bulidSuccess([], '设置淘汰成功');

        } catch (\Exception $exception) {
            Db::rollback();
            return static::bulidFail('设置淘汰失败');
        }
    }

    public function closed()
    {
        if (!ctype_digit($id = $this->post('id', ''))) {
            return static::bulidFail('球队ID不能为空');
        }

        if (!$model = WorldCupGameModel::where('id', $id)->find()) {
            return static::bulidFail('球队不存在');
        }

        if ($model->status == 2) {
            return static::bulidFail('该球队已封盘 不可再次设置');
        }

        $model->status = 2;

        if (!$model->save()) {
            return static::bulidFail('设置封盘失败');
        }

        $this->addAdminLog('成功设置了 ' . $model->team_name . ' 为封盘');

        return static::bulidSuccess([], '设置封盘成功');
    }

    public function champion()
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        if (!ctype_digit($id = $this->post('id', ''))) {
            return static::bulidFail('球队ID不能为空');
        }

        if (!$model = WorldCupGameModel::where('id', $id)->find()) {
            return static::bulidFail('球队不存在');
        }

        if (WorldCupGameModel::where('open_status', 0)->count('id') > 1) {
            return static::bulidFail('世界杯比赛未结束 不可设置为冠军');
        }

        if ($model->open_status == 1) {
            return static::bulidFail('该球队已夺得冠军 不可再次设置');
        }

        $model->status = 2;
        $model->open_status = 1;

        Db::startTrans();

        try {
            if (!$model->save()) {
                Db::rollback();
                return static::bulidFail('设置冠军失败');
            }

            WorldCupGameOrderModel::where('team_id', $id)
                ->where('status', 1)
                ->chunk(100, function ($orders) {
                    $logs = [];
                    $profits = [];
                    foreach ($orders as $order) {
                        if (!$user = UserModel::where('id', $order->user_id)->lock()->find()) {
                            continue;
                        }
                        $order->settle_diamond = bcmul($order->diamond, $order->current_odds, 0);
                        $order->status = 2;
                        if (!$order->save()) {
                            throw new \Exception('订单处理失败');
                        }

                        $user->diamond = $user->diamond + $order->settle_diamond;
                        if (!$user->save()) {
                            throw new \Exception('用户派奖失败' . $user->id);
                        }

                        $profits[] = [
                            'uid' => $order->user_id,
                            'coin_count' => $order->settle_diamond,
                            'content' => '世界杯竞猜派发奖金',
                            'type' => 1,
                            'consume_type' => 22,
                            'order_no' => $order->order_id,
                            'f_uid' => 0,
                            'coin_type' => 2,
                            'resid' => 0,
                            'liveid' => 0,
                            'create_time' => date('Y-m-d H:i:s')
                        ];
                        $logs[] = [
                            'adminid' => $this->admin_id,
                            'content' => $this->admin_name . '为用户 ' . $order->user_id . ' 派发克拉奖金 ' . bcdiv($order->settle_diamond, '100', 2),
                            'create_time' => date('Y-m-d H:i:s'),
                            'uid' => $order->user_id,
                        ];
                    }

                    if ($profits) {
                        if (!(new UserProfitModel())->saveAll($profits)) {
                            throw new \Exception('插入流水记录失败');
                        }
                    }

                    $logs && (new AdminLogModel())->saveAll($logs);
                });

            Db::commit();

            return static::bulidSuccess([], '设置冠军成功');

        } catch (\Exception $exception) {
            Db::rollback();
            return static::bulidFail('设置冠军失败');
        }
    }

    public function order()
    {
        if ($this->request->isAjax()) {
            $model = WorldCupGameOrderModel::field('*');
            if (ctype_digit($mobile = $this->get('mobile', ''))) {
                if (!$user = UserModel::field('id')->where('mobile', $mobile)->find()) {
                    return json([
                        'list' => [],
                        'count' => [],
                        'code' => 0,
                        'msg' => ''
                    ]);
                }
                $model = $model->where('user_id', $user->id);
            } else if ($nick_name = trim($this->get('nick_name', ''))) {
                if (!$user = UserModel::field('id')->where('nick_name', $nick_name)->find()) {
                    return json([
                        'list' => [],
                        'count' => [],
                        'code' => 0,
                        'msg' => ''
                    ]);
                }
                $model = $model->where('user_id', $user->id);
            }

            return json([
                'count' => $model->count('id'),
                'list' => $model->with(
                    [
                        'user' => function (Query $quer) {
                            $quer->field('id,nick_name,mobile');
                        }
                    ])
                    ->order('id', 'desc')
                    ->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()->each(function ($query) {
                        if ($query->diamond) {
                            $query->diamond = bcdiv($query->diamond, '100', 2);
                        }

                        if ($query->settle_diamond) {
                            $query->settle_diamond = bcdiv($query->settle_diamond, '100', 2);
                        }

                    })
                    ->toArray(),
                'code' => 0,
                'msg' => ''
            ]);
        }

        return $this->fetch();
    }
}